import os, sys, copy

parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 4)))
sys.path.insert(0, parent_path)

import traceback, requests,threading
import numpy as np
import time
import socket, json, cv2
from typing import *
from core.task.modules.processors.base_processor import BaseProcessor
from core.utils.logger import logging
from core.utils.general import download_imgs

class HttpRequest(BaseProcessor):
    """将数据通过http回传到接口
    """
    def __init__(self, keys, HttpRequest_url = None, HttpRequest_delay=0, HttpRequest_timeout = 20) -> None:
        self.keys = keys
        self.url = HttpRequest_url
        self.delay_time = HttpRequest_delay
        self.timeout = HttpRequest_timeout
        self.last_post_time = time.time()

    def _init_check(self):
        assert not self.url is None        
        assert "in" in self.keys

    def _set(self, data:Dict):
        if data.get("HttpRequest_url",False):
            self.url = data[self.keys["HttpRequest_url"]]
        if data.get("HttpRequest_timeout",False):
            self.timeout = data[self.keys["HttpRequest_timeout"]]
    
    def request_post_json(self,json_data):
        try:
            requests.post(url=self.url,json=json_data,timeout=self.timeout,verify=False)
            logging.info("|success post json to {}|".format(self.url))
        except:
            logging.error(traceback.format_exc())

    def _call(self, data:Dict) -> Dict:
        if time.time() - self.last_post_time > self.delay_time:
            if data.get(self.keys["in"], False):
                json_data = data.pop(self.keys["in"])
                threading.Thread(target=self.request_post_json,args=(json_data,)).start()
                self.last_post_time = time.time()
        return data

class HttpDownload(BaseProcessor):
    """通过HTTP协议下载图片
    """
    def __init__(self, keys, HttpDownload_timeout = 20) -> None:
        self.keys = keys
        self.timeout = HttpDownload_timeout

    def _init_check(self):
        assert "in" in self.keys
        assert "out" in self.keys

    def _set(self, data:Dict):
        if data.get("HttpRequest_timeout",False):
            self.timeout = data[self.keys["HttpRequest_timeout"]]

    def _call(self, data:Dict) -> Dict:
        ret, img_list = download_imgs(data[self.keys["in"]])
        if not ret:
            raise Exception("Http download Fail")
        # input_np = np.stack(img_list,0) if len(img_list)>1 else img_list[0][None,...]
        data[self.keys["out"]] = img_list
        return data


if __name__ == "__main__":
    print("")
